<?php
namespace plugins\member_login\controller;
use think\Db;
use plugins\member\model\MemberModel;
use cmf\controller\ApiThirdAccessBaseController;
use plugins\member\interfaceLib\MemberClassify;
use plugins\finance\model\FinanceModel;
/**
 * 手机号码控制器
 */
class ApiPhoneAutoController extends ApiThirdAccessBaseController
{
	public function regiest($add)
	{
		//随机的登录名
		$add['login_name'] = "user_".substr(uniqid(),0,6).mt_rand(1000,9999);
		$add['join_date'] = time();
		$add['join_ip'] = $this->request->ip();
		$add['password'] =  '';
		//默认头像
		$add['head_portrait'] = '/plugins/member/view/public/user.png';
		$m = new MemberModel( $add );
		$result =  $m->allowField( true )->save();
		if( !$result ){
			return api_json_echo( false , '注册失败' );
		}
		//uid的补充
	    $res=str_pad($m->id,4,"0",STR_PAD_LEFT);   
		$uid = 'zy_'.$res.mt_rand(1000,9999);
		$model = MemberModel::get($m->id);
		$model->uid = $uid;
		$model->nick_name = $uid;
		//加密的uid
		$aes = new MemberClassify;
		$model->uid_aes = $aes->aesSetUid($uid);
		$model->save();
		//返回反馈信息
		$data['token'] = $this->setIdentity($uid);
		$data['refresh_token'] = $this->setRefreshToken($uid);	
		$data['aes'] = $model->uid_aes;
		//创建财务账户
		( new FinanceModel )->createFinanceAccount('member',$uid);
		return api_json_echo( true , '会员注册成功',$data );
	}
	//手机验证码登陆
	public function login($param)
	{
		//没有直接注册    phone code
		$check_member = ( new MemberModel )->get(['phone'=>$param['phone']]);
		//该手机没有注册
		if($check_member == null){
			$this->regiest($param);
		}
		$check = MemberModel::get(['phone'=>$param['phone']]);
		if($check->status == 1){
			//修改登陆时间与ip
			$Member = ( new MemberModel )->get([ 'phone' => $param['phone'] , 'status' => 1 ]);
            $param['last_date'] = time();
            $param['last_ip'] = $this->request->ip();
			$result = $Member->allowField(true)->save($param);
			if($result){
				//生成token
				$data['token'] = $this->setIdentity($check->uid);
				$data['refresh_token'] = $this->setRefreshToken($check->uid);
				$data['aes'] = $check->uid_aes;
				return api_json_echo( true , '会员登录成功' , $data );
			}else{
				return api_json_echo( false , '会员登录失败，请检查号码' );
			}
		}else if($check->status == 2){
			return api_json_echo( false , '该用户被禁用，请重试' );
		}else if($check->status == 3){
		}
		return api_json_echo( false , '会员登录失败，请检查号码' );
	}
}